package com.jxd.petMgr.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebFilter(filterName = "LoginControlFilter")
public class LoginControlFilter implements Filter {
    public void destroy() {
    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        //session中没有admin说明没有登录，跳转到登录页面
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;

        //取全局变量 request.getServletContext() 对应的是jsp的application
        ServletContext context = request.getServletContext();
        String url = context.getInitParameter("unCheckUrl");
        //将url拆分为字符串数组，每个元素都是一个地址
        String[] urls = url.split(",");

        //取当前路径
        String currentPath = request.getServletPath();
        if (currentPath.endsWith(".html")
                || currentPath.endsWith(".css")
                || currentPath.endsWith(".js")
                || currentPath.endsWith(".png")) {
            //静态资源直接放行
            chain.doFilter(req, resp);
            return;
        }
        //判断当前路径是否为白名单
        for (String path : urls) {
            //判断是静态资源直接放行


            if (currentPath.equals(path)) {
                //白名单直接放行结束方法
                chain.doFilter(req, resp);
                return;
            }
        }


        HttpSession session = request.getSession();
        //session中没有admin
        if (session.getAttribute("petOwner") == null) {
            //即使进行了重定向后面的代码仍然会执行
            response.sendRedirect("login.jsp");


        } else {
            chain.doFilter(req, resp);
        }

    }

    public void init(FilterConfig config) throws ServletException {

    }

}
